import React, { useState, useEffect } from "react";
import { getProductList } from "../../api";
import { Table, Image, Form, Button, Input } from "antd";
import type { ColumnsType } from "antd/es/table";
import "./home.css";

// 定义产品接口
interface Product {
  id: number;
  name: string;
  category: string;
  price: number;
  stock: number;
  createdAt: string;
  description: string;
  image: string;
}

// 定义 API 响应格式
interface ApiResponse {
  code?: number;
  list: Product[];
  count: number;
}

// 定义搜索表单值类型
interface SearchFormValues {
  name?: string;
}

const columns: ColumnsType<Product> = [
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
    width: "10%",
    align: "center",
  },
  {
    title: "类别",
    dataIndex: "category",
    key: "category",
    align: "center",
    width: "10%",
  },
  {
    title: "价格",
    dataIndex: "price",
    key: "price",
    align: "center",
    width: "10%",
    render: (text: number) => <span>￥{text.toFixed(2)}</span>,
  },
  {
    title: "库存",
    dataIndex: "stock",
    align: "center",
    key: "stock",
    width: "10%",
  },
  {
    title: "创建日期",
    dataIndex: "createdAt",
    key: "createdAt",
    align: "center",
    width: "15%",
  },
  {
    title: "描述",
    dataIndex: "description",
    key: "description",
    align: "center",
    width: "25%",
    render: (text: string) => (
      <div style={{ maxWidth: "500px", wordBreak: "break-all" }}>{text}</div>
    ),
  },
  {
    title: "图片",
    dataIndex: "image",
    align: "center",
    key: "image",
    width: "20%",
    render: (text: string) => <Image src={text} alt="商品" width={200} />,
  },
];

const Product: React.FC = () => {
  const [productList, setProductList] = useState<Product[]>([]);

  const getList = () => {
    getProductList().then((res: ApiResponse) => {
      console.log(res);
      setProductList(res.list);
    });
  };

  useEffect(() => {
    getList();
  }, []);

  const handleFinish = (values: SearchFormValues) => {
    console.log("Search values:", values);
    // 这里添加搜索逻辑
  };

  return (
    <div className="home">
      <div className="top">
        <Form<SearchFormValues> layout="inline" onFinish={handleFinish}>
          <Form.Item name="name">
            <Input placeholder="请输入商品名称" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Table<Product>
        dataSource={productList}
        columns={columns}
        rowKey="id"
        scroll={{
          y: "calc(100vh - 300px)",
          x: "100%",
        }}
        pagination={{
          pageSizeOptions: ["10", "20", "50"],
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
      />
    </div>
  );
};

export default Product;
